<?php

/**
 *  * 系统-受国家计算机软件著作权保护 - !
 * =========================================================
 * Copy right 2018-2025 成都海之心科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.ohyu.cn
 * 这不是一个自由软件！在未得到官方有效许可的前提下禁止对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * User: ohyueo
 * Date: 2021/5/17
 * Time: 14:17
 */

namespace app\admin\controller;
use think\facade\View;
use app\admin\traits\AdminAuth;
use think\facade\Db;
use app\admin\models\EscortAdmin;
use app\admin\models\EscortAdminActionLog;
use app\admin\models\EscortAdminRole;
use app\admin\models\EscortAdminUserRole;
use app\admin\models\EscortAdminPermission;
use app\admin\models\EscortAdminRolePermission;

class Admin extends Common
{
    use AdminAuth;

    public function actionlog(){
        if(request()->isPost()){
            $page=input("param.page");
            $where = array();
            if(!$page){
                $page=1;
            }
            $limit=input("param.limit");
            if(!$limit){
                $limit=10;//每页显示条数
            }
            $pre = ($page-1)*$limit;//起始页数
            $str=input("param.str");
            $end=input("param.end");
            if($str && $end){
                $str=strtotime($str);
                $end=strtotime($end);
                $where['addtime'] = array('between',[$str,$end]);
            }
            //根据模型里面的baseModel方法获取数据
            $count=EscortAdminActionLog::countData(['where'=>$where]);
            $data=EscortAdminActionLog::findAllData(['where'=>$where,'page'=>$page,'limit'=>$limit,'order'=>'id desc']);
            //$data = EscortAdmin::getActionLogData($where,$str,$end,$pre,$limit);
            $res = ['code' => 0, 'message' => '请求成功', 'data' => $data, 'count' => $count];
            return json($res);
        }
        return View::fetch();
    }

    public function userlist()
    {
        $permis = $this->getPermissions('Admin/userlist');
        View::assign('data', $this->actions);
        View::assign('permis', $permis);
        $roles = Db::name('escort_admin_role')->field('Id, name')->select();
        View::assign('roles', $roles);
        if(request()->isPost()){
            $page=input("param.page");
            $where = array();
            $username = input('param.username');
            if ($username) {
                $where['a.username'] = array('like', '%'.$username.'%');
            }
            $name = input('param.name');
            if ($name) {
                $where['a.name'] = array('like', '%'.$name.'%');
            }
            $role_id = input('param.role_id');
            if ($role_id) {
                $where['r.id'] = $role_id;
            }
            $where2=[];
            //根据模型里面的baseModel方法获取数据
            $escort_admin_merid=session('escort_admin_merid');
            if($escort_admin_merid){
                $where['a.merid']=$escort_admin_merid;
                $where2['merid']=$escort_admin_merid;
            }
            $count = Db::name('escort_admin')->where($where2)->count();
            $data = Db::name('escort_admin')->alias('a')->join('escort_admin_user_role ur', 'a.id = ur.admin_id', 'LEFT')
            ->join('escort_admin_role r', 'ur.role_id = r.id', 'LEFT')
            ->where($where)->field('a.id, a.username, a.name, a.status, a.addtime, a.lastlogin, a.text, r.name role')->select();
            $res = ['code' => 0, 'message' => '请求成功', 'data' => $data, 'count' => $count];
            return json($res);
        }
        return View::fetch();
    }

    public function adduser()
    {
        if (request()->isGet()) {
            //根据模型里面的baseModel方法查询多条数据
            $roles = EscortAdminRole::findAllData(['where'=>['id'=>'!=1','wei'=>1]]);
            View::assign('roles', $roles);
            return View::fetch();
        }else{
            //账号不能重复添加
            $name=input('username');
            //根据模型里面的baseModel方法获取数据
            $res=EscortAdmin::countData(['where'=>['username'=>$name,'wei'=>1]]);
            //$res=Db::name('escort_admin')->where('username',$name)->count();
            if($res){
                $res = ['status' => 0, 'msg' => '添加账号不能和现有账号重复'];
                return json($res);
            }
            $data = [
                'username' => input('username'),
                'name' => input('name'),
                'password' => md5('*&>'.md5(input('password'))),
                'status' => 1,
                'lastlogin' => 0,
                'addtime' => time()
            ];
            //根据模型里面的baseModel方法添加数据
            $result=EscortAdmin::addData($data);
            $result = $result->id;
            //$result = Db::name('escort_admin')->insertGetId($data);
            if ($result) {
                $arr=[
                    'admin_id' => $result,
                    'role_id' => input('role_id')
                ];
                //根据模型里面的baseModel方法添加数据
                EscortAdminUserRole::addData($arr);
                //Db::name('escort_admin_user_role')->insert($arr);
                $text = '新增了后台人员 '.input('username');
                $this->writeActionLog($text);
                $res = ['status' => 1, 'msg' => '添加成功'];
            } else {
                $res = ['status' => 0, 'msg' => '添加失败'];
            }
            return json($res);
        }
    }

    public function edituser()
    {
        if (request()->isGet()) {
            $id = input('id');
            $where2=$where=[];
            $escort_admin_merid=session('escort_admin_merid');
            if($escort_admin_merid){
                $where['a.merid']=$escort_admin_merid;
                $where2['merid']=$escort_admin_merid;
            }
            $admin = Db::name('escort_admin')->alias('a')->join('escort_admin_user_role r', 'r.admin_id = a.id', 'LEFT')
            ->where($where)
            ->field('a.username, a.id, a.name, r.role_id')->where('a.id', $id)->find();
            $roles = Db::name('escort_admin_role')->where('id', '<>', 1)->where($where2)->select();
            View::assign('admin', $admin);
            View::assign('roles', $roles);
            return View::fetch();
        } else {
            $data = [
                'username' => input('username'),
                'name' => input('name')
            ];
            if (input('password')) {
                $data['password'] = md5('*&>'.md5(input('password')));
            }
            //根据模型里面的baseModel方法更新数据
            $result=EscortAdmin::updatesData(['where'=>['id'=>input('id')],'data'=>$data]);
            //$result = Db::name('escort_admin')->where('id', input('id'))->update($data);
            if ($result !== false) {
                //根据模型里面的baseModel方法更新数据
                EscortAdminUserRole::updatesData(['where'=>['admin_id'=>input('id')],'data'=>['role_id'=>input('role_id')]]);
                //Db::name('escort_admin_user_role')->where('admin_id', input('id'))->update(['role_id'=> input('role_id')]);
                $text = '修改了后台人员ID为 '.input('id').'的资料';
                $this->writeActionLog($text);
                $res = ['status' => 1, 'msg' => '修改成功'];
            } else {
                $res = ['status' => 0, 'msg' => '修改失败'];
            }
            return json($res);
        }
    }

    public function deluser()
    {
        $id = input('id');

        if (!$id) {
            $res = ['status' => 0, 'message' => '删除失败'];
            return json($res);
        }
        $id = explode(',', $id);
        $id = array_filter($id);
        //根据模型里面的baseModel方法查询多个字段
        $names=EscortAdmin::columnData(['where'=>['id'=>['in',$id]],'field'=>'username']);
        //$names = Db::name('escort_admin')->where('id', 'in', $id)->column('username');
        //根据模型里面的baseModel方法删除数据
        $result=EscortAdmin::deleteData(['where'=>['id'=>['in',$id]]]);
        //$result = Db::name('escort_admin')->delete($id);
        if ($result) {
            //根据模型里面的baseModel方法删除数据
            EscortAdminUserRole::deleteData(['where'=>['admin_id'=>['in',$id]]]);
            //Db::name('escort_admin_user_role')->where('admin_id', 'in', $id)->delete();
            $text = '删除了后台人员 '.implode(',', $names);
            $this->writeActionLog($text);
            $res = ['status' => 1, 'message' => '删除成功'];
        } else {
            $res = ['status' => 0, 'message' => '删除失败'];
        }
        return json($res);
    }

    public function rolelist()
    {
        $permis = $this->getPermissions('Admin/rolelist');
        View::assign('data', $this->actions);
        View::assign('permis', $permis);
        if(request()->isPost()) {
            $page = input("param.page",1);
            //根据模型里面的baseModel方法获取数据
            $count=EscortAdminRole::countData([]);
            $data=EscortAdminRole::findAllData(['page'=>$page,'limit'=>10]);
            //$count = Db::name('escort_admin_role')->count();
            //$data = Db::name('escort_admin_role')->page($page, 10)->select();
            $res = ['code' => 0, 'message' => '请求成功', 'data' => $data, 'count' => $count];
            return json($res);
        }
        return View::fetch();
    }

    public function addrole()
    {
        if (request()->isGet()) {
            //根据模型里面的baseModel方法获取数据
            //$permis = EscortAdminPermission::findAllData([]);
            $permis = Db::name('escort_admin_permission')->select();
            $permis = tree($permis);
            View::assign('permis', $permis);
            return View::fetch();
        } else {
            $data = input('post.');
            //添加角色
            //根据模型里面的baseModel方法添加数据
            $role_id=EscortAdminRole::addData(['name'=>$data['name'],'text'=>$data['text']]);
            $role_id = $role_id->id;
            // $role_id = Db::name('escort_admin_role')->insertGetId([
            //     'name' => $data['name'],
            //     'text' => $data['text']
            // ]);
            $permis = implode(',', $data['limits']);
            if ($role_id) {
                //根据模型里面的baseModel方法添加数据
                $result=EscortAdminRolePermission::addData(['role_id'=>$role_id,'permission_id'=>$permis]);
                // $result = Db::name('escort_admin_role_permission')->insert([
                //     'role_id' => $role_id,
                //     'permission_id' => $permis
                // ]);
                if ($result) {
                    $text = '新增了角色 '.input('name');
                    $this->writeActionLog($text);
                    $res = ['status' => 1, 'message' => '添加成功'];
                } else {
                    $res = ['status' => 2, 'message' => '添加失败'];
                }
            } else {
                $res = ['status' => 2, 'message' => '添加失败'];
            }
            return json($res);
        }
    }

    public function delrole()
    {
        $id = input('id');

        if (!$id) {
            $res = ['status' => 0, 'message' => '删除失败'];
            return json($res);
        }
        $id = explode(',', $id);
        $id = array_filter($id);

        //根据模型里面的baseModel方法查询多个字段
        $names=EscortAdminRole::columnData(['where'=>['id'=>['in',$id]],'field'=>'name']);
        //$names = Db::name('escort_admin_role')->where('id', 'in', $id)->column('name');

        //根据模型里面的baseModel方法删除数据
        $result=EscortAdminRole::deleteData(['where'=>['id'=>['in',$id]]]);
        //$result = Db::name('escort_admin_role')->delete($id);
        if ($result) {
            //根据模型里面的baseModel方法删除数据
            EscortAdminRolePermission::deleteData(['where'=>['role_id'=>['in',$id]]]);
            //Db::name('escort_admin_role_permission')->where('role_id', 'in', $id)->delete();
            $text = '删除了角色 '.implode(',', $names);
            $this->writeActionLog($text);
            $res = ['status' => 1, 'message' => '删除成功'];
        } else {
            $res = ['status' => 2, 'message' => '删除失败'];
        }
        return json($res);
    }

    public function editrole()
    {
        if (request()->isGet()) {
            $id = input('id');
            $where2=$where=[];
            $escort_admin_merid=session('escort_admin_merid');
            if($escort_admin_merid){
                $where['r.merid']=$escort_admin_merid;
                $where2['merid']=$escort_admin_merid;
            }
            $role = Db::name('escort_admin_role')->alias('r')->join('escort_admin_role_permission p', 'p.role_id = r.id', 'LEFT')
            ->where($where)
            ->where('r.id', $id)->field('r.id, r.name, r.text, p.permission_id')->find();
            //根据模型里面的baseModel方法获取数据
            //$permis=EscortAdminPermission::findAllData(['order'=>'p_id asc,id asc']);
            $permis = Db::name('escort_admin_permission')->order('p_id asc,id asc')->select();
            $permis = tree($permis);
            View::assign('role', $role);
            View::assign('permis', $permis);
            return View::fetch();
        } else {
            $data = input('param.');
            //根据模型里面的baseModel方法更新数据
            $result=EscortAdminRole::updatesData(['where'=>['id'=>$data['id']],'data'=>['name'=>$data['name'],'text'=>$data['text']]]);
            // $result = Db::name('escort_admin_role')->where('id',$data['id'])->update([
            //     'name' => $data['name'],
            //     'text' => $data['text']
            // ]);
            if ($result !== false) {
                if($data && @count($data['limits'])>0){
                    $permis = implode(',', $data['limits']);
                }else{
                    $permis='';
                }
                //根据模型里面的baseModel方法更新数据
                $result=EscortAdminRolePermission::updatesData(['where'=>['role_id'=>$data['id']],'data'=>['permission_id'=>$permis]]);
                //$result = Db::name('escort_admin_role_permission')->where('role_id', $data['id'])->update(['permission_id'=>$permis]);
                $text = '修改了角色资料 '.$data['name'];
                $this->writeActionLog($text);
                $res = ['status' => 1, 'message' => '修改成功'];
            } else {
                $res = ['status' => 2, 'message' => '修改失败'];
            }
            return json($res);
        }
    }
}